<?php
// **************************************************************
// | Name: 星空框架  阿里云推送处理
// **************************************************************
// | Version: V5.0
// **************************************************************
// | Author: xkyinzhe <zhonghuaxinxing@sina.cn>
// **************************************************************
// | City: 青岛
// **************************************************************
// | Time: 2021-12-06 10:23
// **************************************************************
declare(strict_types=1);

namespace app\common\services;

use app\common\model\User as UserModel;
use think\facade\Cache;
use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
use AlibabaCloud\Push\Push;

/**
 * @xk 执行阿里云推送
 */
class AliPushMsg
{
    /**
     * @xk 执行信息推送
     *
     * @method sendMsg
     * @param  [type]     $device_id                 [description]
     * @param  [type]     $be_from                   [description]
     * @return [type]     [description]
     * @Time   2021-12-06
     * @City   青岛
     * @Author xkyinzhe   <zhonghuaxinxing@sina.cn>
     */
    public static function sendMsg($device_id, $be_from, $title, $content,$jobKey='')
    {
        if($device_id != ''){
          switch ($be_from) {
            case 'android':
              self::androidSend($device_id, $title, $content,$jobKey);
              break;
            case 'ios':
              self::iosSend($device_id, $title, $content,$jobKey);
              break;
          }
        }
        $path = 'alisend/';
        createLog($path, $content);
    }
    /**
     * @xk 安卓消息推送
     *
     * @method androidSend
     * @param  [type]      $device_id                 [description]
     * @param  [type]      $content                   [description]
     * @return [type]      [description]
     * @Time   2021-12-06
     * @City   青岛
     * @Author xkyinzhe    <zhonghuaxinxing@sina.cn>
     */
    public static function androidSend($device_id, $title, $content,$jobKey)
    {
        // echo $device_id; die();
        AlibabaCloud::accessKeyClient((string)config('core_config.ali_push_config.al_access_key'), (string)config('core_config.ali_push_config.al_access_secret'))
                                ->regionId('cn-hangzhou')
                                ->asDefaultClient();
        $path = 'alisend/';
        $contentx = "【安卓】".$content."/n";
        try {
            $result = AlibabaCloud::rpc()
                                  ->product('Push')
                                  ->scheme('https') // https | http
                                  ->version('2016-08-01')
                                  ->action('Push')
                                  ->method('POST')
                                  ->host('cloudpush.aliyuncs.com')
                                  ->options([
                                                'query' => [
                                                  'RegionId' => "cn-hangzhou",
                                                  'AppKey' => (string)config('core_config.ali_push_config.android_key'), // AppKey
                                                  'PushType' => "NOTICE", // MESSAGE=消息 NOTICE=通知
                                                  'DeviceType' => "ALL", // iOS ANDROID ALL
                                                  'Target' => "DEVICE", // DEVICE=根据设备 ACCOUNT=根据账号推送 ALIAS=根据别名 TAG=根据标记 ALL=全部推送
                                                  'TargetValue' => $device_id,
                                                  'Body' => $content,
                                                  'Title' => $title,
                                                  'StoreOffline' => "true", // 离线消息通知 默认false
                                                  "jobKey" => $jobKey,
                                                  // 'PushTime' => "2021-12-12 15:05:0", // 定时推送
                                                  // 'ExpireTime' => "2021-12-12 15:05:01", // 离线推送过期时间 和StoreOffline配合使用
                                                  'AndroidNotifyType' => "BOTH", //提醒方式 VIBRATE：振动（默认值）SOUND：声音 BOTH：声音和振动 NONE：静音
                                                  'AndroidOpenType' => "APPLICATION", // APPLICATION：打开应用（默认值）ACTIVITY：打开应用AndroidActivity URL：打开URL NONE：无跳转
                                                  'AndroidActivity' => "com.alibaba.cloudpushdemo.bizactivity", // 仅当AndroidOpenType=”Activity”时传入，如：com.alibaba.cloudpushdemo.bizactivity。
                                                  // 'AndroidOpenUrl' => "https://github.com/aliyun/openapi-sdk-php100", // 打开的链接
                                                  'AndroidNotificationBarType' => "100", // 自定义通知栏样式 1-100
                                                  'AndroidNotificationBarPriority' => "-2", // 通知栏排列优先级 -2 - 2
                                                  // 'AndroidNotificationXiaomiChannel' => "sdafsdafsd", // 小米通知类型 需要再小米平台申请
                                                  'AndroidNotificationChannel' => '1', // 针对安卓8以上机型特殊设置
                                                  // 'AndroidNotificationVivoChannel' => "0", //设置vivo通知消息分类，取值为：0：运营类消息（默认）1：系统类消息 需要在vivo平台申请。
                                                  // 'AndroidNotificationHuaweiChannel' => "NORMAL",
                                                  // 'AndroidMessageHuaweiUrgency' => "HIGH", //华为通道透传消息投递优先级，取值如下：HIGH NORMAL 需要申请权限。
                                                  // 'AndroidMessageHuaweiCategory' => "PLAY_VOICE", // 华为通道标识高优先级透传消息的特殊场景，取值如下：PLAY_VOICE：语音播报 VOIP：VoIP电话。
                                                  // 'SendChannels' => "1", //指定发送通道（测试中功能，仅可用于纯安卓应用），取值如下：accs：阿里自有通道 huawei：华为通道 xiaomi：小米通道 meizu：魅族通道 vivo：vivo通道 oppo：OPPO通道 测试中
                                                  // setAndroidNotificationChannel
                                                ],
                                            ])
                                  ->request();
          $contentx .="推送成功";
          createLog($path,$contentx);
          return 1;
        } catch (ClientException $e) {
            $contentx.="因为".$e->getErrorMessage() .'推送失败';
            createLog($path,$contentx);
          return 0;
        } catch (ServerException $e) {
          return 0;
          $contentx.="因为".$e->getErrorMessage() .'推送失败';
          createLog($path,$contentx);

        }
    }
    /**
     * @xk 苹果端消息推送
     *
     * @method iosSend
     * @param  [type]     $device_id                 [description]
     * @param  [type]     $content                   [description]
     * @return [type]     [description]
     * @Time   2021-12-06
     * @City   青岛
     * @Author xkyinzhe   <zhonghuaxinxing@sina.cn>
     */
    public static function iosSend($device_id, $title, $content,$jobKey)
    {
        $path = 'alisend/';
        $contentx = "【苹果推送】".$content."/n";
        AlibabaCloud::accessKeyClient((string)config('core_config.ali_push_config.al_access_key'), (string)config('core_config.ali_push_config.al_access_secret'))
                              ->regionId('cn-hangzhou')
                              ->asDefaultClient();
        try {
            $result = AlibabaCloud::rpc()
                                ->product('Push')
                                ->scheme('https') // https | http
                                ->version('2016-08-01')
                                ->action('Push')
                                ->method('POST')
                                ->host('cloudpush.aliyuncs.com')
                                ->options([
                                              'query' => [
                                                'RegionId' => "cn-hangzhou",
                                                'AppKey' => (string)config('core_config.ali_push_config.ios_app_key'), // AppKey
                                                'PushType' => "NOTICE", // MESSAGE=消息 NOTICE=通知
                                                'DeviceType' => "ALL", // iOS ANDROID ALL
                                                'Target' => "DEVICE", // DEVICE=根据设备 ACCOUNT=根据账号推送 ALIAS=根据别名 TAG=根据标记 ALL=全部推送
                                                'TargetValue' => $device_id,
                                                'Body' => $content,
                                                'Title' => $title,
                                                'StoreOffline' => "true", // 离线消息通知 默认false
                                                "jobKey" => $jobKey,
                                                // 'PushTime' => "2021-12-12 15:05:0", // 定时推送
                                                // 'ExpireTime' => "2021-12-12 15:05:01", // 离线推送过期时间 和StoreOffline配合使用
                                                'iOSApnsEnv' => "PRODUCT", // 苹果端环境 DEV=测试 PRODUCT=生产环境
                                                'iOSRemind' => "true", // 是否离线启动其他推送通道
                                                'iOSRemindBody' => $content, // 离线推送内容
                                                'iOSBadgeAutoIncrement' => "true", // 开启ios角标自增功能
                                                'iOSSilentNotification' => "true", // ios静默通知
                                              ],
                                          ])
                                ->request();
            $contentx .="推送成功";
            return 1;
        } catch (ClientException $e) {
            $contentx.="因为".$e->getErrorMessage() .'推送失败';
            return 0;
        } catch (ServerException $e) {
            $contentx.="因为".$e->getErrorMessage() .'推送失败';
            return 0;
        }
        createLog($path,$contentx);
    }
}
